package me.flyray.bsin.server.biz;

import me.flyray.bsin.cache.BsinCacheProvider;
import me.flyray.bsin.server.domain.AiModel;
import me.flyray.bsin.server.domain.TenantWxPlatform;
import me.flyray.bsin.server.domain.TenantWxPlatformUser;
import me.flyray.bsin.server.mapper.*;
import me.flyray.bsin.thirdauth.wx.builder.TextBuilder;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import me.flyray.bsin.thirdauth.wx.handler.AbstractHandler;
import me.flyray.bsin.thirdauth.wx.utils.BsinWxMpServiceUtil;
import me.flyray.bsin.utils.BsinSnowflake;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;

/**
 * @author <a href="https://github.com/binarywang">Binary Wang</a>
 */
@Component
public class SubscribeHandlerBiz extends AbstractHandler {

    @Autowired
    private AiModelMapper aiModelMapper;
    @Autowired
    private AiTenantWxPlatformMapper tenantWxmpMapper;
    @Autowired
    private AiTenantWxPlatformRoleMapper tenantWxmpRoleMapper;
    @Autowired
    private AiTenantWxPlatformUserMapper tenantWxmpUserMapper;
    @Autowired
    private AiTenantWxPlatformUserTagMapper tenantWxmpUserTagMapper;
    @Autowired
    BsinWxMpServiceUtil bsinWxMpServiceUtil;
    @Autowired
    private BsinCacheProvider bsinCacheProvider;

    @Value("${bsin.ai.aesKey}")
    private String aesKey;

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                    Map<String, Object> context, WxMpService weixinService,
                                    WxSessionManager sessionManager) throws WxErrorException {

        this.logger.info("新关注用户 OPENID: " + wxMessage.getFromUser());

        String appId = bsinCacheProvider.get(wxMessage.getFromUser());
        String openId = wxMessage.getFromUser();
        TenantWxPlatform tenantWxPlatform = tenantWxmpMapper.selectByAppId(appId);
//        WxMpProperties.MpConfig config = new WxMpProperties.MpConfig();
//        config.setAesKey(tenantWxPlatform.getAesKey());
//        config.setAppId(appId);
//        SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, aesKey.getBytes());
//        config.setSecret(aes.decryptStr(tenantWxPlatform.getAppSecret(), CharsetUtil.CHARSET_UTF_8));
//        config.setToken(tenantWxPlatform.getTokenId());

        AiModel aiModel = aiModelMapper.selectBySerialNo(tenantWxPlatform.getAiModelNo());
        // 获取微信用户基本信息
        try {
            WxMpUser userWxInfo = weixinService.getUserService()
                    .userInfo(wxMessage.getFromUser(), null);
            if (userWxInfo != null) {
                // TODO 可以添加关注用户到本地数据库
                // 判断用户是否存在
                System.out.println("插入用户数据表");
                TenantWxPlatformUser tenantWxPlatformUser = tenantWxmpUserMapper.selectByOpenId(openId);
                if (tenantWxPlatformUser == null) {
                    tenantWxPlatformUser = new TenantWxPlatformUser();
                    tenantWxPlatformUser.setTenantId(tenantWxPlatform.getTenantId());
                    tenantWxPlatformUser.setOpenId(openId);
                    tenantWxPlatformUser.setAppId(appId);
                    tenantWxPlatformUser.setSerialNo(BsinSnowflake.getId());
                    tenantWxPlatformUser.setCreateTime(new Date());
                    tenantWxmpUserMapper.insert(tenantWxPlatformUser);
                }
            }
        } catch (WxErrorException e) {
            if (e.getError().getErrorCode() == 48001) {
                this.logger.info("该公众号没有获取用户信息权限！");
            }
        }

        WxMpXmlOutMessage responseResult = null;
        try {
            responseResult = this.handleSpecial(wxMessage);
        } catch (Exception e) {
            this.logger.error(e.getMessage(), e);
        }

        if (responseResult != null) {
            return responseResult;
        }

        try {
            return new TextBuilder().build(aiModel.getSubscribeResponse(), wxMessage, weixinService);
        } catch (Exception e) {
            this.logger.error(e.getMessage(), e);
        }

        return null;
    }

    /**
     * 处理特殊请求，比如如果是扫码进来的，可以做相应处理
     */
    private WxMpXmlOutMessage handleSpecial(WxMpXmlMessage wxMessage)
            throws Exception {
        //TODO
        return null;
    }

}